var createError = require("http-errors");
var express = require("express");
var path = require("path");
var cookieParser = require("cookie-parser");
var logger = require("morgan");

var indexRouter = require("./routes/index");
var usersRouter = require("./routes/users");
let cors = require("cors");
var app = express();
const { expressjwt } = require("express-jwt");
// const auth = require("./authorization");
// view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "jade");
app.use(cors());
app.use(
  expressjwt({
    secret: "secretKey",
    algorithms: ["HS256"],
  }).unless({
    path: ["/login", "/refresh", "/newCoverForEducationImg", /^\/upload\/*/, /^\/wang*\/*/],
  })
);

app.use(logger("dev"));
//解析的请请求体数据
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));
app.use("/upload", express.static(path.join("upload")));
app.use("/", indexRouter);
app.use("/users", usersRouter);
// app.use("/upload", express.static(path.join("upload")));
// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

app.use(function (err, req, res, next) {
  // token解析失败
  console.log(req.headers, 1111);
  const authorization = req.headers["authorization"];
  if (!authorization) {
    return res.status(401).json({
      code: 20000,
      msg: "用户未登录",
    });
  }
  if (err.name === "UnauthorizedError") {
    return res.status(401).json({
      code: 20000,
      msg: "登录过期，请重新登录",
    });
  }

});

module.exports = app;
